import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:sui_shou_pai/Utils/storage_util.dart';
import 'package:sui_shou_pai/module/color.dart';
import 'package:sui_shou_pai/my/init_info/init_information.dart';
import 'package:sui_shou_pai/network/http_config.dart';
import 'package:sui_shou_pai/network/http_request.dart';
import 'package:sui_shou_pai/news/data/news_list_item_data.dart';
import 'package:sui_shou_pai/news/news/news_list_item.dart';

import 'liked_news.dart';

class LikedCompanyNewsList extends StatefulWidget {
  LikedCompanyNewsList({
    Key key,
  }) : super(key: key);

  @override
  LikedCompanyNewsListState createState() => LikedCompanyNewsListState();
}

class LikedCompanyNewsListState extends State<LikedCompanyNewsList> {
  List<dynamic> tempList = [];
  List<LikedNews> likedNews = [];
  List<NewsListItemData> newsList = [];
  int pageNum;
  int pages;
  String loading;

  ScrollController _scrollController;
  bool isLoading = false;

  @override
  void initState() {
    super.initState();
    pageNum = 1;
    loading = "加载中";
    Future.delayed(
        Duration.zero,
        () => setState(() {
              initData();
            }));
    _scrollController = ScrollController();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels >=
              _scrollController.position.maxScrollExtent &&
          pageNum < pages) {
        print('滑到了底部');
        _loadMore();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    // 新闻数据
    List<Widget> items = List.generate(likedNews.length, (int index) {
      return Container(
        padding: EdgeInsets.symmetric(vertical: 16),
        decoration: BoxDecoration(
          border: Border(
            bottom: BorderSide(width: 1, color: greyF6F6F6),
          ),
        ),
        child: Column(
          children: [
            Container(
              padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Icon(
                    Icons.thumb_up,
                    color: Colors.red,
                  ),
                  Text(
                    likedNews[index].likeTime,
                    textAlign: TextAlign.left,
                    style: TextStyle(fontSize: 15, color: Colors.grey),
                  ),
                ],
              ),
            ),
            initNewsListItem(context, newsList[index])
          ],
        ),
      );
    });

    return ListView.builder(
      itemBuilder: (context, index) {
        if (index < items.length) {
          return items[index];
        } else {
          return _buildLoadMoreItem();
        }
      },
      controller: _scrollController,
      padding: EdgeInsets.fromLTRB(10, 0, 10, 20),
      itemCount: items.length + 1,
    );
  }

  initData() async {
    HttpRequest.request("$BASE_URL/news-like/getLikedNews",
            method: "post",
            data: {
              "employeeId": await StorageUtil.getStringItem("employeeId"),
              "pageNum": "1",
              "pageSize": "5"
            },
            token: await StorageUtil.getStringItem("token"))
        .then((value) {
      setState(() {
        tempList = json.decode(value.toString())['result']['records'];
        pages = json.decode(value.toString())['result']['pages'];
        if (pageNum == pages) {
          loading = "你已滑到世界尽头";
        }
      });
      for (int i = 0; i < tempList.length; i++) {
        likedNews.add(LikedNews.fromMap(tempList[i]));
        newsList.add(NewsListItemData(
          tempList[i]['newsId'],
          tempList[i]['title'],
          tempList[i]['time'].toString().substring(0, 10),
          tempList[i]['source'],
          tempList[i]['content'],
          tempList[i]['headerImage'],
        ));
      }
    });
  }

  Future<Null> _loadMore() async {
    if (!isLoading) {
      setState(() {
        isLoading = true;
      });

      await Future.delayed(Duration(seconds: 2), () {
        setState(() {
          isLoading = false;
          if (pageNum < pages) {
            pageNum = pageNum + 1;
            if (pageNum == pages) {
              loading = "你已滑到世界尽头";
            }
            HttpRequest.request("$BASE_URL/news-comment/getCommentedNews",
                method: "post",
                data: {
                  "employeeId": InitInformation.employeeId,
                  "pageNum": pageNum.toString(),
                  "pageSize": "5"
                }).then((value) {
              List<dynamic> loadMoreData = [];
              setState(() {
                loadMoreData =
                    json.decode(value.toString())['result']['records'];
                for (int i = 0; i < loadMoreData.length; i++) {
                  likedNews.add(LikedNews.fromMap(loadMoreData[i]));
                  newsList.add(NewsListItemData(
                    loadMoreData[i]['newsId'],
                    loadMoreData[i]['title'],
                    (loadMoreData[i]['time']).toString().substring(0, 10),
                    loadMoreData[i]['source'],
                    loadMoreData[i]['content'],
                    loadMoreData[i]['headerImage'],
                  ));
                }
              });
            });
          } else {}
        });
      });
    }
  }

  Widget _buildLoadMoreItem() {
    return Center(
      child: Padding(
        padding: EdgeInsets.all(10.0),
        child: Text(loading),
      ),
    );
  }
}
